<template>
    <div class="screen">
        <header class="topbar">
            <button class="icon-btn" @click="goBack" aria-label="back">
                <svg viewBox="0 0 24 24" width="24" height="24">
                    <path fill="currentColor" d="M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
                </svg>
            </button>
            <div class="title">词库</div>
        </header>

        <!-- 固定区域：搜索、分类、筛选 -->
        <div class="fixed-section">
            <div class="search" :class="{ focused: searchFocused }">
                <svg class="search-icon" viewBox="0 0 24 24" width="18" height="18">
                    <path fill="currentColor" d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
                </svg>
                <input
                    class="search-input"
                    v-model.trim="searchTerm"
                    placeholder="输入词书名称搜索"
                    @focus="handleSearchFocus"
                    @blur="handleSearchBlur"
                />
                <button class="search-clear" v-if="searchTerm" @mousedown.prevent="clearSearch">×</button>
                <ul class="search-suggestions" v-if="showSuggestions">
                    <li
                        v-for="item in suggestionItems"
                        :key="item.id"
                    >
                        <button type="button" @mousedown.prevent="selectSuggestion(item.name)">
                            {{ item.name }}
                            <span class="count">{{ item.wordCount }}词</span>
                        </button>
                    </li>
                </ul>
            </div>

            <div class="tabs">
                <button 
                    v-for="t in tabs" 
                    :key="t" 
                    :class="['tab', { active: selectedCategory === t }]"
                    @click="handleCategoryChange(t)"
                >
                    {{ t }}
                </button>
            </div>

            <div class="chips">
                <button 
                    v-for="chip in filterChips" 
                    :key="chip" 
                    :class="['chip', { active: selectedFilter === chip }]"
                    @click="selectedFilter = chip"
                >
                    {{ chip }}
                </button>
            </div>
        </div>

        <!-- 可滚动区域：单词书列表 -->
        <div class="scrollable-list">
            <div v-if="isLoading" class="loading">加载中...</div>
            <div v-else-if="!filteredBookItems.length" class="empty">未找到相关词书</div>
            <div v-for="b in filteredBookItems" :key="b.id" class="book" @click="selectWordbook(b)">
                <div class="cover" :style="b.coverStyle" :class="{ 'has-image': b.hasImage }">
                    <div class="cover-content" v-if="!b.hasImage" :style="{ color: b.textColor }">
                        <div class="cover-text">
                            <span v-for="line in b.coverLines" :key="line">{{ line }}</span>
                        </div>
                    <div class="cover-icon" v-if="b.coverIcon">{{ b.coverIcon }}</div>
                    </div>
                </div>
                <div class="meta">
                    <div class="name">{{ b.name }}</div>
                    <div class="desc" v-if="b.description">{{ b.description }}</div>
                    <div class="stats">{{ b.wordCount }}词</div>
                    <div class="status" v-if="b.status">{{ b.status }}</div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { fetchWordbooks, fetchStudyTasks, switchWordbook } from '@/utils/api.js'
import { generateWordbookCover } from '@/utils/coverPalette.js'

const router = useRouter()
function goBack(){ router.back() }

const fallbackBooks = [
    { id: 1, name: '生词本', wordCount: 4642, status: '正在学习' },
    { id: 2, name: '六级词汇闪过', wordCount: 5298, description: '收词详尽，重点突出', status: '收藏' },
    { id: 3, name: '除单词本外的生词本', wordCount: 0 },
    ...Array.from({length: 12}).map((_, i) => ({
        id: `sample-${i}`,
        name: `示例词书 ${i + 1}`,
        wordCount: 300 + i * 8,
    })),
]

const books = ref(fallbackBooks)
const isLoading = ref(false)
const searchTerm = ref('')
const searchFocused = ref(false)
const learnedWordbookIds = ref(new Set()) // 存储用户学过的词书ID
let blurTimer = null

async function loadWordbooks() {
    isLoading.value = true
    try {
        const data = await fetchWordbooks()
        if (Array.isArray(data) && data.length > 0) {
            books.value = data
        }
    } catch (error) {
        console.error('加载词书失败:', error)
    } finally {
        isLoading.value = false
    }
}

// 加载用户的学习任务，获取学过的词书ID
async function loadStudyTasks() {
    try {
        const tasks = await fetchStudyTasks()
        if (Array.isArray(tasks) && tasks.length > 0) {
            // 提取所有学过的词书ID（去重）
            // 支持多种可能的字段名：wordbook_id, wordbookId
            const ids = new Set()
            tasks.forEach(task => {
                const wordbookId = task.wordbook_id || task.wordbookId
                if (wordbookId) {
                    ids.add(wordbookId)
                }
            })
            learnedWordbookIds.value = ids
            console.log('已学习的词书ID:', Array.from(ids))
        }
    } catch (error) {
        console.error('加载学习任务失败:', error)
    }
}

// 选择词书并切换
async function selectWordbook(book) {
    if (!book || !book.id) {
        console.warn('无效的词书数据:', book)
        return
    }
    
    try {
        console.log('切换词书:', book.name, 'ID:', book.id)
        // 调用API切换词书
        await switchWordbook(book.id)
        // 切换成功后跳转到Dashboard
        router.push({ name: 'dashboard' })
    } catch (error) {
        console.error('切换词书失败:', error)
        // 可以显示错误提示
        alert('切换词书失败，请重试')
    }
}

onMounted(() => {
    loadWordbooks()
    loadStudyTasks()
})

const selectedCategory = ref('我的')
const selectedFilter = ref('全部')

const tabs = ['我的','大学','高中','初中']

// 根据选中的分类动态显示筛选条件
const filterChips = computed(() => {
    if (selectedCategory.value === '我的') {
        return ['全部', '自制']
    } else if (selectedCategory.value === '大学') {
        return ['全部', '四六级', '英专', '考研', '专升本', 'ab级']
    } else {
        // 高中、初中暂时只显示"全部"
        return ['全部']
    }
})

const baseBookItems = computed(() => books.value.map((book, index) => {
    const id = book.id ?? `book-${index}`
    const name = book.name || `词书 ${index + 1}`
    const wordCount = book.words ?? book.wordCount ?? 0
    const description = book.desc ?? book.description ?? ''
    const status = book.status ?? book.state ?? ''
    const coverUrl = book.coverUrl ?? ''

    const hasImage = typeof coverUrl === 'string' && coverUrl.trim().length > 0
    const coverMeta = hasImage ? null : generateWordbookCover(name)
    const coverLines = hasImage
        ? []
        : (Array.isArray(book.coverLines) && book.coverLines.length > 0
            ? book.coverLines
            : book.coverText
                ? String(book.coverText).split(/\n+/)
                : coverMeta.lines)

    const coverIcon = hasImage ? '' : (book.coverIcon || coverMeta.icon)
    const textColor = hasImage ? '#fff' : (book.textColor || coverMeta.textColor)

    const coverStyle = hasImage
        ? {
            backgroundImage: `url(${coverUrl})`,
            backgroundSize: 'cover',
            backgroundPosition: 'center',
            backgroundRepeat: 'no-repeat',
        }
        : {
            background: book.coverGradient || coverMeta.gradient,
        }

    return {
        ...book,
        id,
        name,
        wordCount,
        description,
        status,
        hasImage,
        coverStyle,
        coverIcon,
        coverLines,
        textColor,
    }
}))


const normalized = (value = '') => value.toString().toLowerCase()

// 切换分类时重置筛选条件
function handleCategoryChange(category) {
    selectedCategory.value = category
    selectedFilter.value = '全部' // 切换分类时重置为"全部"
}

const filteredBookItems = computed(() => {
    let result = baseBookItems.value
    
    // 按分类筛选
    if (selectedCategory.value === '我的') {
        // "我的"分类：从学习任务表中获取学过的词书
        if (selectedFilter.value === '全部') {
            // 显示所有学过的词书（根据学习任务表中的wordbook_id）
            result = result.filter(book => {
                return learnedWordbookIds.value.has(book.id)
            })
        } else if (selectedFilter.value === '自制') {
            // 显示自制的词书（且是学过的）
            result = result.filter(book => {
                const isLearned = learnedWordbookIds.value.has(book.id)
                const isSelfMade = book.source === '自制' || 
                                  book.type === '自制' ||
                                  book.tag === '自制'
                return isLearned && isSelfMade
            })
        }
    } else if (selectedCategory.value === '大学') {
        // "大学"分类：根据筛选条件筛选
        if (selectedFilter.value !== '全部') {
            result = result.filter(book => {
                const category = book.category || book.type || book.class || ''
                const name = normalized(book.name)
                const desc = normalized(book.description || '')
                
                // 根据筛选条件匹配
                if (selectedFilter.value === '四六级') {
                    // 四六级：包含四级或六级，但排除专四、专八
                    const hasFourOrSix = name.includes('四级') || name.includes('六级') || 
                                        name.includes('cet') || desc.includes('四六级')
                    const isSpecialized = name.includes('专四') || name.includes('专八') ||
                                         name.includes('专业四级') || name.includes('专业六级')
                    return hasFourOrSix && !isSpecialized
                } else if (selectedFilter.value === '英专') {
                    // 英专：包含英专、专业、专四、专八
                    return name.includes('英专') || name.includes('专业') ||
                           name.includes('专四') || name.includes('专八') ||
                           name.includes('专业四级') || name.includes('专业六级') ||
                           name.includes('专业八级')
                } else if (selectedFilter.value === '考研') {
                    return name.includes('考研') || desc.includes('考研')
                } else if (selectedFilter.value === '专升本') {
                    return name.includes('专升本') || desc.includes('专升本')
                } else if (selectedFilter.value === 'ab级') {
                    return name.includes('a级') || name.includes('b级') ||
                           name.includes('A级') || name.includes('B级') ||
                           name.includes('英语a级') || name.includes('英语b级')
                }
                return category === selectedFilter.value
            })
        }
    } else if (selectedCategory.value === '高中') {
        // 高中分类：通过词书名称和描述进行智能匹配
        result = result.filter(book => {
            const name = normalized(book.name)
            const desc = normalized(book.description || '')
            return name.includes('高中') || name.includes('高考') ||
                   desc.includes('高中') || desc.includes('高考')
        })
    } else if (selectedCategory.value === '初中') {
        // 初中分类：通过词书名称和描述进行智能匹配
        result = result.filter(book => {
            const name = normalized(book.name)
            const desc = normalized(book.description || '')
            return name.includes('初中') || name.includes('中考') ||
                   desc.includes('初中') || desc.includes('中考')
        })
    }
    
    // 按搜索词筛选
    const term = normalized(searchTerm.value.trim())
    if (term) {
        result = result.filter((book) => {
            const name = normalized(book.name)
            const desc = normalized(book.description || '')
            return name.includes(term) || desc.includes(term)
        })
    }
    
    return result
})

const suggestionItems = computed(() => {
    const term = normalized(searchTerm.value.trim())
    if (!term) return []
    return baseBookItems.value
        .filter((book) => normalized(book.name).includes(term))
        .slice(0, 8)
})

const showSuggestions = computed(() => searchFocused.value && suggestionItems.value.length > 0)

function handleSearchFocus() {
    if (blurTimer) {
        clearTimeout(blurTimer)
        blurTimer = null
    }
    searchFocused.value = true
}

function handleSearchBlur() {
    blurTimer = setTimeout(() => {
        searchFocused.value = false
    }, 120)
}

function selectSuggestion(name) {
    searchTerm.value = name
    searchFocused.value = false
}

function clearSearch() {
    searchTerm.value = ''
    searchFocused.value = false
}
</script>

<style scoped>
.screen { 
    position: fixed; 
    inset: 0; 
    background: #fff; 
    display: flex; 
    flex-direction: column; 
    overflow: hidden;
}

.topbar { 
    height: 56px; 
    display: flex; 
    align-items: center; 
    gap: 12px; 
    padding: 0 16px; 
    border-bottom: 1px solid #f1f5f9;
    flex-shrink: 0;
}

.title { 
    font-weight: 700; 
    font-size: 18px; 
    color: #111827;
}

.icon-btn { 
    border: none; 
    background: transparent; 
    cursor: pointer; 
    color: #111827;
    padding: 4px;
    display: flex;
    align-items: center;
}

/* 固定区域 */
.fixed-section {
    flex-shrink: 0;
    padding: 12px 16px 0;
    background: #fff;
    border-bottom: 1px solid #f1f5f9;
}

.search { 
    position: relative;
    padding: 4px 0 12px; 
}

.search.focused .search-input {
    border-color: #6366f1;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15);
}

.search-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #9ca3af;
    pointer-events: none;
}

.search-input { 
    width: 100%; 
    height: 40px; 
    padding: 0 12px 0 40px; 
    border-radius: 8px; 
    border: 1px solid #e5e7eb; 
    background: #f3f4f6;
    font-size: 14px;
    color: #111827;
}

.search-input:focus {
    outline: none;
}

.search-clear {
    position: absolute;
    right: 10px;
    top: 50%;
    transform: translateY(-50%);
    border: none;
    background: transparent;
    color: #9ca3af;
    font-size: 18px;
    line-height: 1;
    cursor: pointer;
    padding: 2px;
}

.search-clear:hover {
    color: #6b7280;
}

.search-suggestions {
    position: absolute;
    left: 0;
    right: 0;
    top: calc(100% - 6px);
    background: #fff;
    border-radius: 10px;
    border: 1px solid #e5e7eb;
    box-shadow: 0 12px 24px rgba(15, 23, 42, 0.12);
    padding: 6px 0;
    z-index: 20;
    max-height: 240px;
    overflow-y: auto;
}

.search-suggestions li button {
    width: 100%;
    padding: 10px 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: none;
    background: transparent;
    cursor: pointer;
    font-size: 14px;
    color: #111827;
}

.search-suggestions li button:hover {
    background: rgba(99, 102, 241, 0.08);
}

.search-suggestions .count {
    font-size: 12px;
    color: #6b7280;
}

.search-input::placeholder {
    color: #9ca3af;
}

.tabs { 
    display: flex; 
    gap: 12px; 
    padding: 12px 0; 
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.tabs::-webkit-scrollbar {
    display: none;
}

.tab { 
    position: relative;
    background: transparent; 
    border: none; 
    color: #6b7280; 
    font-weight: 600; 
    padding: 6px 2px; 
    cursor: pointer;
    white-space: nowrap;
    font-size: 14px;
}

.tab.active { 
    color: #111827; 
    border-bottom: 2px solid #ff6a00;
}

.hot-badge {
    position: absolute;
    top: -8px;
    right: -8px;
    background: #ef4444;
    color: #fff;
    font-size: 10px;
    font-weight: 700;
    padding: 1px 4px;
    border-radius: 4px;
    line-height: 1.2;
}

.chips { 
    display: flex; 
    gap: 10px; 
    padding-bottom: 12px; 
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

.chips::-webkit-scrollbar {
    display: none;
}

.chip { 
    border: 1px solid #f1f5f9; 
    background: #fff; 
    padding: 6px 12px; 
    border-radius: 999px; 
    cursor: pointer; 
    color: #6b7280;
    font-size: 14px;
    white-space: nowrap;
    transition: all 0.2s;
}

.chip.active { 
    background: #ff6a00; 
    color: #fff; 
    border-color: #ff6a00;
}

/* 可滚动列表区域 */
.scrollable-list { 
    flex: 1; 
    overflow-y: auto; 
    padding: 12px 16px;
    -webkit-overflow-scrolling: touch;
}

.book { 
    display: grid; 
    grid-template-columns: 64px 1fr; 
    gap: 12px; 
    padding: 12px; 
    border-radius: 12px; 
    border: 1px solid #f1f5f9; 
    background: #fff; 
    box-shadow: 0 2px 8px rgba(0,0,0,.04);
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.2s ease;
}

.book:hover {
    border-color: #6366f1;
    box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
    transform: translateY(-2px);
}

.book:active {
    transform: translateY(0);
    box-shadow: 0 2px 8px rgba(0,0,0,.08);
}

.cover { 
    width: 64px; 
    height: 84px; 
    border-radius: 8px; 
    position: relative;
    overflow: hidden;
    box-shadow: 0 2px 6px rgba(0,0,0,.15);
    display: flex;
    align-items: stretch;
    justify-content: center;
}

.cover.has-image {
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

.cover-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 100%;
    padding: 12px 6px 10px;
}

.cover-icon {
    font-size: 24px;
    line-height: 1;
}

.cover-text {
    display: flex;
    flex-direction: column;
    gap: 2px;
    font-weight: 700;
    font-size: 13px;
    line-height: 1.1;
    width: 100%;
    word-break: break-word;
    text-align: center;
}

.cover-text span {
    display: block;
}

.meta {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.name { 
    font-weight: 700; 
    color: #111827;
    font-size: 16px;
}

.desc {
    color: #6b7280;
    font-size: 13px;
    margin-top: 2px;
}

.stats { 
    color: #6b7280; 
    font-size: 13px;
    margin-top: 4px;
}

.status {
    color: #ff6a00;
    font-size: 13px;
    font-weight: 600;
    margin-top: 4px;
}

.loading,
.empty {
    text-align: center;
    color: #6b7280;
    padding: 40px 0;
}
</style>
